package com.formula.datastructure.exercise.list;

/**
 * ADT
 * getLength
 * insert(data)
 * find(data)
 * update(idx, data)
 * getByIdx(idx)
 * deleteByIdx(idx)
 * deleteByData(data)
 */
public class SeqList {
    private Integer[] array;

    private int length;

    public SeqList() {
        array = new Integer[50];
    }

    public SeqList(int size) {
        array = new Integer[size];
    }

    public int getLength() {
        return length;
    }

    public int insert(Integer data) {
        if (length < array.length) {
            array[length++] = data;
        }
        return 0;
    }

    public int find(Integer data) {
        for (int i = 0; i < length; i++) {
            if (array[i] == data) {
                return i;
            }
        }
        return -1;
    }

    public int update(int idx, Integer data) {
        if (idx < length) {
            array[idx] = data;
            return 1;
        }
        return 0;
    }

    public Integer get(int idx) {
        if (idx >= length) {
            return null;
        }
        return array[idx];
    }

    public Integer deleteByIdx(int idx) {
        if (idx >= length) {
            return null;
        }
        Integer result = array[idx];
        array[idx] = null;
        length--;
        return result;
    }

    public int deleteByData(Integer data) {
        int idx = find(data);
        if (idx == -1) {
            return 0;
        }
        deleteByIdx(idx);
        return 1;
    }
}
